<template>
  <el-card class="container">
    <header>
      <!-- 右侧新增试题 -->
      <div class="addTopic">
        <el-button type="success" size="small" @click="$router.push('new')">
          <i class="el-icon-edit"></i>新增试题
        </el-button>
      </div>
      <!-- 表单区域 -->
      <div class="screenForm">
        <el-form label-width="80px" ref="ruleForm">
          <el-row>
            <el-col :span="6">
              <!-- 学科 -->
              <el-form-item label="学科" size="small">
                <el-select
                  placeholder="请选择"
                  v-model="form.subjectID"
                  @focus="getSubjectList()"
                  style="width:100%;"
                >
                  <el-option
                    v-for="(item,index) in subjectList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 二级目录 -->
              <el-form-item label="二级目录" size="small">
                <el-select
                  placeholder="请选择"
                  v-model="form.catalogID"
                  @focus="getTwoLevelList()"
                  style="width:100%;"
                >
                  <el-option
                    v-for="(item,index) in twoLevelList"
                    :key="index"
                    :label="item.directoryName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 标签 -->
              <el-form-item label="标签" size="small">
                <el-select placeholder="请选择" v-model="form.tags" style="width:100%;"></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 关键字 -->
              <el-form-item label="关键字" size="small">
                <el-input v-model="form.keyword"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 试题类型 -->
              <el-form-item label="试题类型" size="small">
                <el-select placeholder="请选择" v-model="form.questionType" style="width:100%;"></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 难度 -->
              <el-form-item label="难度" size="small">
                <el-select placeholder="请选择" v-model="form.difficulty" style="width:100%;"></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 方向 -->
              <el-form-item label="方向" size="small">
                <el-select placeholder="请选择" v-model="form.direction" style="width:100%;"></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 录入人 -->
              <el-form-item label="录入人" size="small">
                <el-select placeholder="请选择" v-model="form.creatorID" style="width:100%;"></el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 题目备注 -->
              <el-form-item label="题目备注" size="small">
                <el-input v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 企业简称 -->
              <el-form-item label="企业简称" size="small">
                <el-input v-model="form.shortName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 城市 -->
              <el-form-item label="城市" size="small">
                <el-select placeholder="请选择" style="width:48%;margin-right:2%" v-model="form.city"></el-select>
                <el-select placeholder="请选择" style="width:50%" v-model="form.formArea"></el-select>
              </el-form-item>
            </el-col>
            <!-- 清除和搜索按钮 -->
            <el-col :span="6">
              <el-form-item class="functionButton" size="small">
                <el-button @click="resetForm()">清除</el-button>
                <el-button type="primary" @click="search()">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </header>
    <footer>
      <!-- 整个表格区域 -->
      <!-- 总数据 -->
      <div class="top">
        <div class="total">
          <i class="el-icon-info"></i>
          数据一共 {{total}} 条
        </div>
      </div>
      <!-- 表格 -->
      <div class="center">
        <el-table :data="formDataList" style="width: 100%">
          <el-table-column prop="number" label="试题编号" width="120"></el-table-column>
          <el-table-column prop="subject" label="学科" width="105"></el-table-column>
          <el-table-column prop="catalog" label="目录" width="103"></el-table-column>
          <el-table-column :formatter="statusFormatter" prop="questionType" label="题型" width="103"></el-table-column>
          <el-table-column prop="question" label="题干" width="280">
            <template slot-scope="scope">{{delHtmlTag(scope.row.question)}}</template>
          </el-table-column>
          <el-table-column prop="addDate" :formatter="formatter" label="录入时间" width="180"></el-table-column>
          <el-table-column :formatter="statusDifficulty" prop="difficulty" label="难度" width="103"></el-table-column>
          <el-table-column prop="creator" label="录入人" width="103"></el-table-column>
          <el-table-column prop="address" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="warning"
                icon="el-icon-view"
                circle
                plain
                size="small"
                @click="previewClick(scope.row)"
                title="预览"
              ></el-button>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-edit"
                circle
                plain
                @click="$router.push(`new?id=${scope.row.id}`)"
                title="修改"
              ></el-button>
              <el-button
                size="small"
                type="danger"
                icon="el-icon-delete"
                circle
                plain
                @click="delTopic(scope.row)"
                title="删除"
              ></el-button>
              <el-button
                size="small"
                type="success"
                icon="el-icon-check"
                circle
                plain
                @click="addChoice(scope.row)"
                title="加入精选"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="bottom">
        <el-pagination
          style="margin-top:20px;text-align:right"
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-size="pagesize"
          :current-page="page"
          @current-change="pageNumber"
          :page-sizes="[5,10,20,50]"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
      <!-- 预览 -->
      <QualityDialog ref="questionPreview" :data="questionInfo"></QualityDialog>
    </footer>
  </el-card>
</template>

<script>
import { list, remove, choiceAdd } from '@/api/hmmm/questions'
import QualityDialog from '../components/questions-preview'
import { simple as subjectList } from '@/api/hmmm/subjects'
import { list as catalogList } from '@/api/hmmm/directorys'

export default {
  data () {
    return {
      page: 1,
      pagesize: 5,
      total: 0,
      formDataList: [], // list, remove, choiceAdd
      questionInfo: {}, /// 预览组件
      form: {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        city: '', // 城市
        formArea: ''// 城市中的省份
      },
      subjectList: [], // 学科
      twoLevelList: []// 二级目录
    }
  },
  components: {
    QualityDialog
  },
  mounted () {

  },
  watch: {
    // 由于上一种监听每次对象属性变化都会导致handler执行，只想监听对象中某个属性变化
    'form.subjectID': {
      handler (newValue, oldValue) {
        this.form.catalogID = ''
        this.form.tags = ''
      }
    }
  },
  created () {
    this.list()
  },
  methods: {
    async list () {
      const { data } = await list({
        page: this.page,
        pagesize: this.pagesize
      })
      this.formDataList = data.items
      this.total = data.counts
    },
    // 获取科目列表
    async getSubjectList () {
      const data = await subjectList()
      this.subjectList = data.data
    },
    // 根据科目获取其二级列表数据
    async getTwoLevelList () {
      const data = await catalogList({ subjectID: this.form.subjectID })
      this.twoLevelList = data.data.items
    },
    // 格式化表格里的录入时间
    formatter (row, column, cellValue) {
      let format = 'YYYY-mm-dd HH:MM:SS'
      const date = new Date(cellValue)
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString()
      }
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format)
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'))
        }
      })
      return format
    },
    // 后台传过来的数值转换成对应的数据渲染题型是什么类型
    statusFormatter (row, column) {
      const status = row.questionType
      if (status === '1') {
        return '单选'
      } else if (status === '2') {
        return '多选'
      } else if (status === '3') {
        return '简答'
      }
    },
    // 后台传过来的数值转换成对应的数据渲染题型是什么难度
    statusDifficulty (row, column) {
      const status = row.difficulty
      if (status === '1') {
        return '简单'
      } else if (status === '2') {
        return '一般'
      } else if (status === '3') {
        return '困难'
      }
    },
    // 去除后端返回给我们的数据（题干）中的标签
    delHtmlTag (str) {
      return str.replace(/<[^>]+>/g, '').replace(/&nbsp;/ig, '')
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
    },
    // 删除表格中的题目
    async delTopic (val) {
      await this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(val)
      this.$message.success('删除成功')
      this.list()
    },
    // 加入精选题库
    async addChoice (val) {
      await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      })
      await choiceAdd({ id: val.id, choiceState: 1 })
      this.$message.success('加入精选成功')
      this.page = 1
      this.list()
    },
    // 预览
    previewClick (val) {
      this.questionInfo = val
      this.$nextTick(() => {
        this.$refs.questionPreview.open()
      })
    },
    // pageSize 改变时会触发此函数
    handleSizeChange (size) {
      this.page = 1
      this.pagesize = size
      this.list()
    },
    // 页码改变时触发此函数，参数就是当前点击的页码值
    pageNumber (val) {
      this.page = val
      this.list()
    },
    // 清空表单
    resetForm () {
      this.form = {
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        city: '' // 城市
      }
    },
    // 搜索功能
    async search () {
      const newForm = {}
      Object.keys(this.form).forEach(item => {
        if (this.form[item] !== '') {
          newForm[item] = this.form[item]
        }
      })
      const { data } = await list({ ...this.page, ...newForm })
      this.formDataList = data.items
      this.total = data.counts
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  margin: 10px;
  border-radius: 5px;
  header {
    position: relative;
    .addTopic {
      display: flex;
      justify-content: right;
      margin-bottom: 16px;
      i {
        margin-right: 5px;
      }
    }
    .functionButton {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
  footer {
    .top {
      color: #909399;
      .total {
        height: 35px;
        width: 100%;
        padding: 10px 16px;
        display: inline-block;
        background-color: #f4f4f5;
        border-radius: 4px;
        font-size: 13px;
        margin-bottom: 15px;
        i {
          width: 16px;
          height: 16px;
          text-align: center;
          line-height: 16px;
          border-radius: 50%;
          font-size: 16px;
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
